<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\Activity;
use App\Model\ActivityColumn;

use App\Model\News;
use App\Model\Notify;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;

use Hyperf\Di\Annotation\Inject;
use App\Service\NotifyQueueService;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class ActivityController extends AppBaseController
{

    #[Inject] protected NotifyQueueService $notifyQueueService;

    /**
     * 后台--支部活动栏目
     * @return object
     */
    #[RequestMapping(path:'activityColumn',methods: 'get')]
    public function activityColumn(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            
            $where['status'] = 1;
            $list = ActivityColumn::where($where)->selectRaw('id,name,type')->get();
            $next = 0;
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--支部活动列表
     * @return object
     */
    #[RequestMapping(path:'activityList',methods: 'get')]
    public function activityList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }

            $list = Activity::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,title,status,pass_status,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Activity::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--支部活动详情
     * @param int $activity_id
     * @return object
     */
    #[RequestMapping(path:'activityInfo/{activity_id}',methods: 'get')]
    public function activityInfo(int $activity_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = Activity::where('id',$activity_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 支部活动发布|编辑
     * @param int|null $activity_id
     * @return object
     */
    #[RequestMapping(path: 'activityEdit[/{activity_id}]',methods: 'post,get')]
    public function activityEdit(int|null $activity_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['party_id'] = 1;
//                $data['title'] = '或那个风格二个人哥哥';
                $data['photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['content'] = '学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习';
                $data['media_list'] = [
                    '0'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
                    '1'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
                ];
//                $data['file_list'] = [
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com'],
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com']
//                ];
//                $data['link_url'] = 'https://www.baidu.com';
//                $data['is_show'] = 1;
//                $data['is_long'] = 0;
//                $data['show_start_at'] = '2024-09-01 12:12:12';
//                $data['show_end_at'] = '2024-09-01 12:12:12';
//                $data['status'] = 1;
//            }
            //虚拟数据

            if(empty($data['title'])
                || empty($data['photo'])
            ) return $this->reMsg->re(10007);

            //整理默认参数
            if(empty($data['content'])) $data['content']=null;
            if(empty($data['link_url'])) $data['link_url']=null;
            if(empty($data['media_list']) || !is_array($data['media_list'])) $data['media_list'] = [];
            if(empty($data['file_list']) || !is_array($data['file_list'])) $data['file_list'] = [];
            if(isset($data['is_long']) && $data['is_long']==0){
                if((empty($data['show_start_at']) || empty($data['show_end_at']))) return $this->reMsg->re(10007);
            }else{
                $data['is_long'] = 1;
                $data['show_start_at'] = null;
                $data['show_end_at'] = null;
            }
            empty($data['is_show']) || !is_numeric($data['is_show']) ? $data['is_show'] = 0 : $data['is_show'] = 1;
            empty($data['status']) || !is_numeric($data['status']) ? $data['is_show'] = 0 : $data['is_show'] = 1;

            //指定支部
            if($_admin->level==1){
                if(!isset($data['party_id']) || $data['party_id']==null) return $this->reMsg->re(10007);
                $party_id = $data['party_id'];
            }else{
                $party_id = $_admin->party_id;
            }

            if($activity_id){
                //编辑
                $info = Activity::where('id',$activity_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);

                //判断是否有权操作
                if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);

                $info->title = $data['title'];
                $info->photo = $data['photo'];
                $info->link_url = $data['link_url'];
                $info->content = $data['content'];
                $info->media_list = $data['media_list'];
                $info->is_long = $data['is_long'];
                $info->show_start_at = $data['show_start_at'];
                $info->show_end_at = $data['show_end_at'];
                $info->is_show = $data['is_show'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                if($data['is_show']==1){
                    //查询外链在news的状态
                    $newsInfo = News::where('link_id',$info->id)->first();
                    if($newsInfo){
                        $newsInfo->title = $data['title'];
                        $newsInfo->photo = $data['photo'];
                        $newsInfo->link_url = $data['link_url'];
                        $newsInfo->is_long = $data['is_long'];
                        $newsInfo->show_start_at = $data['show_start_at'];
                        $newsInfo->show_end_at = $data['show_end_at'];
                        $newsInfo->party_id = $party_id;
                        if($data['is_show']==1 && $data['status']==1){
                            $newsInfo->status = 1;
                        }else{
                            $newsInfo->status = 0;
                        }
                        $newsInfo->save();
                    }
                }
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;

                $insertRet = Activity::create($data);
                if($insertRet){
                    if($data['is_show']==1){
                        //说明需要上学习发布首页显示，插入一条数据
                        $newsData['type'] = 3; //支部活动
                        $newsData['title'] = $data['title'];
                        $newsData['photo'] = $data['photo'];
                        $newsData['link_id'] = $insertRet->id;
                        $newsData['link_url'] = $data['link_url'];
                        $newsData['is_long'] = $data['is_long'];
                        $newsData['show_start_at'] = $data['show_start_at'];
                        $newsData['show_end_at'] = $data['show_end_at'];
                        $newsData['status'] = 0; //需要后台审核
//                        if($data['is_show']==1 && $data['status']==1){
//                            $newsData['status'] = 1;
//                        }else{
//                            $newsData['status'] = 0;
//                        }
                        $newsData['party_id'] = $party_id;
                        $newsData['admin_id'] = $_admin->id;
                        $newsInsert = News::create($newsData);
                        if($newsInsert){
                            //执行消息队列任务
                            $this->notifyQueueService->pushNews(['id'=>$newsInsert->id],3);
                        }
                    }
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--活动|审核通过
     * @param int $activity_id
     * @return object
     */
    #[RequestMapping(path:'activityPass/{activity_id}',methods: 'get')]
    public function activityPass(int $activity_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Activity::where('id',$activity_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);
            $info->pass_status = 1;
            $info->save();

            //将newList列表关联数据改为status=1展示状态
            $newWhere['type'] = 3;
            $newWhere['link_id'] = $info->id;
            $newsInfo = News::where($newWhere)->first();
            if($newsInfo){
                $newsInfo->status=1;
                $newsInfo->save();
            }
            //审核通过加积分
            $params = [
                'type'=> 3, //积分类型 type 3:支部活动审核
                'action' => 1, //action 1:加积分 2:减积分
                'party_id' => $info->party_id //支部id
            ];
            $this->makeAdminIntegralLog($params);
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 活动|删除
     * @param int $activity_id
     * @return object
     */
    #[RequestMapping(path:'activityDelete/{activity_id}',methods: 'get')]
    public function activityDelete(int $activity_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            Db::beginTransaction();

            //判断信息
            $info = Activity::where('id',$activity_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);
            $info->delete();

            //删除关联资讯
            $newWhere['type'] = 3; //支部任务
            $newWhere['link_id'] = $info->id;
            $newInfo = News::where($newWhere)->first();

            //删除关联资讯=》通知
            $notifyWhere['module'] = 1;//支部任务（资讯过来的都是 module==1）
            $notifyWhere['relation_id'] = $newInfo->id;
            Notify::where($notifyWhere)->delete();

            $newInfo->delete();
            Db::commit();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }










}